var http = require('http');
var https = require('https');
var util = require('util');
var request = require('request');

// var logger = require('../models/logger');
var utilsHelper = require('../utils/utilsHelper');
var CONSTS = require('../consts.js');

var smsHelper = {
    //计算文字需要多少条短信发送
    getSmsCount: function(s) {
        if (s == '' || !s)
            return 0;
        var len = s.replace(/[^\u0000-\u00ff]/g, "aa").length;
        logger.debug(len);
        return parseInt((len + 69) / 70);
    },
    
    //云通讯sms接口
    sendSms: function(templateId, receiver, msg1, msg2, cb) {
        var time = new Date();
        var timeStamp = time.getFullYear().toString()+
            ((time.getMonth()+1)>9?'':'0')+(time.getMonth()+1)+
            ((time.getDate()+1)>9?'':'0')+(time.getDate()+1)+
            (time.getHours()>9?'':'0')+time.getHours()+
            (time.getMinutes()>9?'':'0')+time.getMinutes()+
            (time.getSeconds()>9?'':'0')+time.getSeconds();   
        var sig = CONSTS.SMS.SID +CONST.SMS.TOKEN + timeStamp;
        logger.debug('sig:', sig);
        var sigParameter = utilsHelper.MD5Crypt(sig).toUpperCase();
        var url = '/2013-12-26/Accounts/' + CONSTS.SMS.SID + '/SMS/TemplateSMS?sig=' + sigParameter;
        //var host = 'sandboxapp.cloopen.com';
        var host = 'app.cloopen.com';
        logger.debug('url:', url);

        var body = {
            'to': receiver,
            'appId': CONSTS.SMS.APPID,
            'templateId': templateId,
            'datas': [msg1]
        };
        body = JSON.stringify(body); 
        logger.debug('body:',body);

        var auth =  utilsHelper.Base64(CONSTS.SMS.SID + ':' + timeStamp);
        var options = {
            hostname: host,
            port: 8883,
            path: url,
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=utf-8',
                'Content-Length': body.length,
                'Authorization' : auth
            },
        };
        logger.debug('options:', options);

        var req = https.request(options, function(res) {
            logger.debug('statusCode: ', res.statusCode);
            logger.debug('headers: ', res.headers);            
            var body = '';
            res.on('data', function(data) {
                body += data;
            }).on('end', function() {
                logger.debug('response body:', body);
                cb(0);
            });
            req.on('error', function(e) {
                logger.debug('err:', e);
                cb(1);
            });
        });
        req.write(body);  
        req.end();
    },

    //世纪云创短信发送
    realsms: function(dest,content,cb) {
        var smsUrl = CONSTS.REALSMS.BASEURL + 'dest=' + dest + '&msg=【塞宾科技】您的登陆验证码为：'+ content +'，10分钟内有效。';
        smsUrl = encodeURI(smsUrl);
        request(smsUrl,function(error, response,body) {
            if (!error && response.statusCode == 200) {
                cb(0);
            }else
                cb(1);
        })
    }
};

module.exports = smsHelper;